<template>
  <div class="flex flex-nowrap">
    <a-button :disabled="selectedKeys.length == 0" @click="upgradeNormal">
      {{ t["升级固件"] }}
    </a-button>

    <a-button @click="batchUpdate">{{ t["批量升级"] }}</a-button>

    <a-button v-auth @click="upgradeHardware"> {{ t["上传固件"] }}</a-button>

    <a-modal @close="onClose" v-model:visible="hardwareModel" :title="t['操作']" :footer="false">
      <div class="flex flex-col gap-4" v-if="!editMode">
        <a-select
          v-model="upgrade.resolution"
          :options="ratioList"
          :placeholder="t['价签尺寸']"
          @change="getVersionList"
        >
        </a-select>
        <a-select
          v-model="upgrade.version"
          :options="upgrade.versionList"
          :placeholder="t['固件版本']"
        >
        </a-select>
        <a-button
          type="primary"
          :disabled="!upgrade.resolution || !upgrade.version"
          long
          v-if="mode"
          @click="oneKeyUpgrade"
        >
          {{ t["升级"] }}
        </a-button>
        <a-button v-else @click="editMode = true">{{ t["下一步"] }}</a-button>
      </div>
      <div v-else>
        <a-textarea v-model="upgrade.idList" :textarea-attrs="{ rows: 16 }"></a-textarea>
        <a-button :disabled="!upgrade.idList" @click="updateList">{{ t["确定"] }}</a-button>
      </div>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { queryApi } from "@/api/selector/query";
import { upgradeLcdDevice } from "@/api/service/lcd-device/lcd-device";
import { listFw, upgradeEslVersion } from "@/api/service/priceTag/priceTag";
import { updateFile } from "@/api/service/utils";

import { useUploadFile } from "@/utils/file";

const t = translate("公共模块");

const props = defineProps<{
  selectedKeys: string[];
  type: "lcd" | "esl";
}>();

const mode = ref(false);

const editMode = ref(false);

const ratioList = ref<any[]>([]);

const hardwareModel = ref(false);

const upgrade = ref({
  versionList: [],
  resolution: "",
  version: "",
  idList: ""
});

const getModelList = async () => {
  if (ratioList.value.length === 0) {
    ratioList.value = await queryApi.queryModel("labelValue", "all");
  }
};

onMounted(() => {
  getModelList();
});
/**
 * 注释: 升级固件
 *
 * */
const upgradeHardware = async () => {
  const file = await useUploadFile("*");
  await updateFile(file, "/firmware/firmware/upload");
};

/**
 * 注释: 获取版本列表
 *
 * */
const getVersionList = async () => {
  const res = await listFw(upgrade.value.resolution);
  upgrade.value.versionList = res.data;
};
function splitBySpaceAndNewline(text: string): string[] {
  // 使用正则表达式按空格或换行分割
  const parts = text.split(/[\s\n]+/);

  // 过滤掉空字符串和仅含逗号的项
  return parts
    .filter((item) => {
      // 移除可能的逗号并检查是否为空
      const trimmed = item.replace(/,/g, "").trim();
      return trimmed.length > 0;
    })
    .map((item) => {
      // 移除末尾可能的逗号
      return item.replace(/,$/, "").trim();
    });
}

const oneKeyUpgrade = async () => {
  let tagList: string[] = [];
  if (editMode.value && upgrade.value.idList) {
    tagList = splitBySpaceAndNewline(upgrade.value.idList);
  }
  let params = {
    firmware: {
      modelId: upgrade.value.resolution,
      version: upgrade.value.version
    },
    tags: editMode.value ? tagList : props.selectedKeys
  };
  if (props.type === "esl") {
    await upgradeEslVersion(params);
  } else {
    await upgradeLcdDevice(params);
  }
  hardwareModel.value = false;
};

const batchUpdate = () => {
  hardwareModel.value = true;
  mode.value = false;
};

const updateList = () => {
  oneKeyUpgrade();
};

const upgradeNormal = () => {
  hardwareModel.value = true;
  mode.value = true;
};
const onClose = () => {
  hardwareModel.value = false;
  editMode.value = false;
  mode.value = false;
  upgrade.value = {
    versionList: [],
    resolution: "",
    version: "",
    idList: ""
  };
};
</script>
